package util.office;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.TCheckReportItem;
import model.VReportImport;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

/** * 
 * 读取word表格导入数据库，支持doc、docx 
 * Modification History: 
 * Date Author Description
 */
public class GetEPQorMHTForWord {

	/**
	 * 根据文件路径列表获取检测报告实体列表
	 * @param fileMap 上传后服务器的文件路径列表
	 * @return 检测报告实体列表
	 * @throws IOException 
	 */
	public List<VReportImport> getVReportImportList(TreeMap<String,InputStream> fileMap) throws IOException {
		List<VReportImport> list = new ArrayList<VReportImport>();
		Iterator iter = fileMap.keySet().iterator();
		while(iter.hasNext())
		{
			String key = (String)iter.next();
			InputStream value = (InputStream)fileMap.get(key);
			VReportImport report = readWordFile2(key,value);
			list.add(report);
		}
		return list;
	}

	/**
	 * 解析EPQ和MHT的Word测评报告
	 * @param request
	 * @param response
	 * @return 
	 * @throws IOException
	 * @throws FileUploadException
	 */
	public static VReportImport readWordFile(HttpServletRequest request, HttpServletResponse response, 
			String classid, String schoolid) throws IOException, FileUploadException{
		
		VReportImport report = new VReportImport();
		List<TCheckReportItem> itemlist = new ArrayList<TCheckReportItem>();
		TCheckReportItem reportItem = null;
		String itemscorestr = "";
		int sortnum = 0;
		
		report.setClassId(classid);
		report.setSchoolid(schoolid);
		
		// 解析 创建上传文件对象
    	ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    	List itemList = upload.parseRequest(request);    		
		for (Iterator it = itemList.iterator(); it.hasNext();) {
			FileItem item = (FileItem) it.next();
			if (!item.isFormField())// 如果是非表单数据（没有放在表单里）
			{
				InputStream ins = item.getInputStream();
				if (item.getName().endsWith("docx")){
					// word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
					XWPFDocument xwpf = new XWPFDocument(ins);// 得到word文档的信息
					List<XWPFParagraph> listParagraphs = xwpf.getParagraphs();// 得到段落信息

					for (int i = 0; i < listParagraphs.size(); i++) {
						XWPFParagraph item1 = (XWPFParagraph) listParagraphs.get(i);
						String txt = item1.getParagraphText();
						if (txt.contains("测评报告")) {						
							report.setCheckname(txt);
							if (txt.contains("少年"))
								report.setPeriod("小学");							
							if (txt.contains("中学生"))
								report.setPeriod("中学");	
						}
						if (txt.contains("测验简介")) {
							XWPFParagraph vitem = (XWPFParagraph) listParagraphs.get(i + 1);
							String info = vitem.getParagraphText();
							report.setCheckintro(info);						
						}

					}
					Iterator<XWPFTable> it1 = xwpf.getTablesIterator();// 得到word中的表格
					Boolean isWeidu = false;
					Boolean isSel = false;
					while (it.hasNext()) {
						XWPFTable table = it1.next();
						List<XWPFTableRow> rows = table.getRows();
						for (int i = 0; i < rows.size(); i++) {
							XWPFTableRow row = rows.get(i);						
							List<XWPFTableCell> cells = row.getTableCells();
							if(cells.size()==10)isSel=true;
							for (int j = 0; j < cells.size(); j++) {
								XWPFTableCell cell = cells.get(j);
								String txt = cell.getText();
								if (txt.contains("登录名")) {
									String[] con = txt.split("：");
									report.setUsername(con[1]);
								}
								if (txt.contains("姓名")) {
									String[] con = txt.split("：");
									report.setRealName(con[1]);
								}
								if (txt.contains("性别")) {
									String[] con = txt.split("：");
									report.setSex(con[1]);
								}
								if (txt.contains("出生日期")) {
									String[] con = txt.split("：");
									report.setBirthday(con[1]);								
								}
								if (txt.contains("完成时间")) {
									String[] con = txt.split("：");
									report.setChecktime(con[1]);								
								}
								if (txt.contains("维度") && i == 0) {
									isWeidu = true;								
									reportItem = new TCheckReportItem();
									String[] con = txt.split(":");
									reportItem.setItemname(con[1]);
								}
								if (isWeidu && txt.contains("原始分") && i == 1) {
									String[] con = txt.split("：");
									reportItem.setOriginalscore(Double.parseDouble(con[1]));								
								}
								if (isWeidu && txt.contains("标准分") && i == 1) {
									String[] con = txt.split("：");
									reportItem.setStandardscore(Double.parseDouble(con[1]));
								}
								if (isWeidu && txt.contains("状态") && i == 1) {
									String[] con = txt.split("：");
									reportItem.setStatus(con[1]);
								}
								if (isWeidu && txt.contains("结果描述") && i == 2) {
									String[] con = txt.split("】");
									reportItem.setResultintro(con[1]);
								}
								if (isWeidu && txt.contains("心理建议") && i == 3) {
									String[] con = txt.split("】");
									reportItem.setSuggestion(con[1]);
									sortnum++;
									reportItem.setSortnum(sortnum);
									itemlist.add(reportItem);								
									isWeidu = false;
								}
								if (isSel) {
									itemscorestr+=txt+"#";
								}
							}
						}
					}
				} 
				else {
					// 如果是office2003 doc格式
					POIFSFileSystem pfs = new POIFSFileSystem(ins);
					HWPFDocument hwpf = new HWPFDocument(pfs);

					Range range = hwpf.getRange();// 得到文档的读取范围

					for (int i = 0; i < range.numParagraphs(); i++) {
						Paragraph p = range.getParagraph(i);
						if (!p.isInTable()) {
							String txt = p.text();
							if (txt.contains("测评报告")) {						
								report.setCheckname(txt);
								if (txt.contains("少年"))
									report.setPeriod("小学");							
								if (txt.contains("中学生"))
									report.setPeriod("中学");	
								if (txt.contains("MHT"))
									report.setChecktypeid(2);
								if (txt.contains("EPQ"))
									report.setChecktypeid(1);
							}
							if (txt.contains("测验简介")) {
								Paragraph vitem = range.getParagraph(i + 1);
								String info = vitem.text();
								report.setCheckintro(info);						
							}						
						}
					}
					// 读取表格
					TableIterator it1 = new TableIterator(range);
					Boolean isWeidu = false;
					Boolean isSel = false;
					// 迭代文档中的表格
					while (it1.hasNext()) {
						Table tb = (Table) it1.next();
						// 迭代行，默认从0开始
						for (int i = 0; i < tb.numRows(); i++) {
							TableRow tr = tb.getRow(i);
							// 迭代列，默认从0开始
							if(tr.numCells()==10)isSel=true;
							for (int j = 0; j < tr.numCells(); j++) {
								TableCell td = tr.getCell(j);// 取得单元格
								String totals = "";
								// 取得单元格的内容
								for (int k = 0; k < td.numParagraphs(); k++) {
									Paragraph para = td.getParagraph(k);
									String s = para.text();
									// 去除后面的特殊符号
									if (null != s && !"".equals(s)) {
										s = s.substring(0, s.length() - 1);
									}
									totals += s;
								}
								String txt = totals;
								if (txt.contains("登录名")) {
									String[] con = txt.split("：");
									report.setUsername(con[1]);
								}
								if (txt.contains("姓名")) {
									String[] con = txt.split("：");
									report.setRealName(con[1]);
								}
								if (txt.contains("性别")) {
									String[] con = txt.split("：");
									report.setSex(con[1]);
								}
								if (txt.contains("出生日期")) {
									String[] con = txt.split("：");
									report.setBirthday(con[1]);								
								}
								if (txt.contains("完成时间")) {
									String[] con = txt.split("：");
									report.setChecktime(con[1]);								
								}
								if (txt.contains("维度") && i == 0) {
									isWeidu = true;
									reportItem = new TCheckReportItem();
									String[] con = txt.split(":");
									reportItem.setItemname(con[1]);
								}
								if (isWeidu && txt.contains("原始分") && i == 1) {
									String[] con = txt.split("：");
									reportItem.setOriginalscore(Double.parseDouble(con[1]));								
								}
								if (isWeidu && txt.contains("标准分") && i == 1) {
									String[] con = txt.split("：");
									reportItem.setStandardscore(Double.parseDouble(con[1]));
								}
								if (isWeidu && txt.contains("状态") && i == 1) {
									String[] con = txt.split("：");
									reportItem.setStatus(con[1]);
								}
								if (isWeidu && txt.contains("结果描述") && i == 2) {
									String[] con = txt.split("】");
									reportItem.setResultintro(con[1]);
								}
								if (isWeidu && txt.contains("心理建议") && i == 3) {
									String[] con = txt.split("】");
									reportItem.setSuggestion(con[1]);
									sortnum++;
									reportItem.setSortnum(sortnum);
									itemlist.add(reportItem);								
									isWeidu = false;
								}
								if (isSel) {
									itemscorestr+=txt+"#";
								}
							}
						}
					}
				}
			}
		}	
		report.setCheckitems(itemlist);	
		report.setItemscorestr(itemscorestr);
		return report;
	}
	
	/**
	 * 解析WORD测评报告
	 * @param filePath Word检测报告路径
	 * @return 检测报告实体
	 * @throws IOException 
	 */
	public VReportImport readWordFile2(String filePath,InputStream ins) throws IOException {
		VReportImport report=new VReportImport();
		List<TCheckReportItem> itemlist=new ArrayList<TCheckReportItem>();
		TCheckReportItem reportItem=null;
		String itemscorestr="";
		int sortnum=0;
	//	try {
			//FileInputStream in = new FileInputStream(filePath);// 载入文档
			// 如果是office2007 docx格式
			if (filePath.toLowerCase().endsWith("docx")) {
				// word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
				XWPFDocument xwpf = new XWPFDocument(ins);// 得到word文档的信息
				List<XWPFParagraph> listParagraphs = xwpf.getParagraphs();// 得到段落信息

				for (int i = 0; i < listParagraphs.size(); i++) {
					XWPFParagraph item = (XWPFParagraph) listParagraphs.get(i);
					String txt = item.getParagraphText();
					if (txt.contains("测评报告")) {						
						report.setCheckname(txt);
						if (txt.contains("少年"))
							report.setPeriod("小学");							
						if (txt.contains("中学生"))
							report.setPeriod("中学");	
					}
					if (txt.contains("测验简介")) {
						XWPFParagraph vitem = (XWPFParagraph) listParagraphs.get(i + 1);
						String info = vitem.getParagraphText();
						report.setCheckintro(info);						
					}

				}
				Iterator<XWPFTable> it = xwpf.getTablesIterator();// 得到word中的表格
				Boolean isWeidu = false;
				Boolean isSel = false;
				while (it.hasNext()) {
					XWPFTable table = it.next();
					List<XWPFTableRow> rows = table.getRows();
					for (int i = 0; i < rows.size(); i++) {
						XWPFTableRow row = rows.get(i);
						List<XWPFTableCell> cells = row.getTableCells();
						if(cells.size()==10)isSel=true;
						for (int j = 0; j < cells.size(); j++) {
							XWPFTableCell cell = cells.get(j);
							String txt = cell.getText();
							if (txt.contains("登录名")) {
								String[] con = txt.split("：");
								report.setUsername(con[1]);
							}
							if (txt.contains("姓名")) {
								String[] con = txt.split("：");
								report.setRealName(con[1]);
							}
							if (txt.contains("性别")) {
								String[] con = txt.split("：");
								report.setSex(con[1]);
							}
							if (txt.contains("出生日期")) {
								String[] con = txt.split("：");
								report.setBirthday(con[1]);								
							}
							if (txt.contains("完成时间")) {
								String[] con = txt.split("：");
								report.setChecktime(con[1]);								
							}
							if (txt.contains("维度") && i == 0) {
								isWeidu = true;								
								reportItem = new TCheckReportItem();
								String[] con = txt.split(":");
								reportItem.setItemname(con[1]);
							}
							if (isWeidu && txt.contains("原始分") && i == 1) {
								String[] con = txt.split("：");
								reportItem.setOriginalscore(Double
										.parseDouble(con[1]));								
							}
							if (isWeidu && txt.contains("标准分") && i == 1) {
								String[] con = txt.split("：");
								reportItem.setStandardscore(Double
										.parseDouble(con[1]));
							}
							if (isWeidu && txt.contains("状态") && i == 1) {
								String[] con = txt.split("：");
								reportItem.setStatus(con[1]);
							}
							if (isWeidu && txt.contains("结果描述") && i == 2) {
								String[] con = txt.split("】");
								reportItem.setResultintro(con[1]);
							}
							if (isWeidu && txt.contains("心理建议") && i == 3) {
								String[] con = txt.split("】");
								reportItem.setSuggestion(con[1]);
								sortnum++;
								reportItem.setSortnum(sortnum);
								itemlist.add(reportItem);								
								isWeidu = false;
							}
							if (isSel) {
								itemscorestr+=txt+"#";
							}
						}
					}
				}
			} else {
				// 如果是office2003 doc格式
				POIFSFileSystem pfs = new POIFSFileSystem(ins);
				HWPFDocument hwpf = new HWPFDocument(pfs);

				Range range = hwpf.getRange();// 得到文档的读取范围

				for (int i = 0; i < range.numParagraphs(); i++) {
					Paragraph p = range.getParagraph(i);
					if (!p.isInTable()) {
						String txt = p.text();
						if (txt.contains("测评报告")) {						
							report.setCheckname(txt);
							if (txt.contains("少年"))
								report.setPeriod("小学");							
							if (txt.contains("中学生"))
								report.setPeriod("中学");	
						}
						if (txt.contains("测验简介")) {
							Paragraph vitem = range.getParagraph(i + 1);
							String info = vitem.text();
							report.setCheckintro(info);						
						}						
					}
				}
				// 读取表格
				TableIterator it = new TableIterator(range);
				Boolean isWeidu = false;
				Boolean isSel = false;
				// 迭代文档中的表格
				while (it.hasNext()) {
					Table tb = (Table) it.next();
					// 迭代行，默认从0开始
					for (int i = 0; i < tb.numRows(); i++) {
						TableRow tr = tb.getRow(i);
						// 迭代列，默认从0开始
						if(tr.numCells()==10)isSel=true;
						for (int j = 0; j < tr.numCells(); j++) {
							TableCell td = tr.getCell(j);// 取得单元格
							String totals = "";
							// 取得单元格的内容
							for (int k = 0; k < td.numParagraphs(); k++) {
								Paragraph para = td.getParagraph(k);
								String s = para.text();
								// 去除后面的特殊符号
								if (null != s && !"".equals(s)) {
									s = s.substring(0, s.length() - 1);
								}
								totals += s;
							}
							String txt = totals;
							if (txt.contains("登录名")) {
								String[] con = txt.split("：");
								report.setUsername(con[1]);
							}
							if (txt.contains("姓名")) {
								String[] con = txt.split("：");
								report.setRealName(con[1]);
							}
							if (txt.contains("性别")) {
								String[] con = txt.split("：");
								report.setSex(con[1]);
							}
							if (txt.contains("出生日期")) {
								String[] con = txt.split("：");
								report.setBirthday(con[1]);								
							}
							if (txt.contains("完成时间")) {
								String[] con = txt.split("：");
								report.setChecktime(con[1]);								
							}
							if (txt.contains("维度") && i == 0) {
								isWeidu = true;
								reportItem = new TCheckReportItem();
								String[] con = txt.split(":");
								reportItem.setItemname(con[1]);
							}
							if (isWeidu && txt.contains("原始分") && i == 1) {
								String[] con = txt.split("：");
								reportItem.setOriginalscore(Double
										.parseDouble(con[1]));								
							}
							if (isWeidu && txt.contains("标准分") && i == 1) {
								String[] con = txt.split("：");
								reportItem.setStandardscore(Double
										.parseDouble(con[1]));
							}
							if (isWeidu && txt.contains("状态") && i == 1) {
								String[] con = txt.split("：");
								reportItem.setStatus(con[1]);
							}
							if (isWeidu && txt.contains("结果描述") && i == 2) {
								String[] con = txt.split("】");
								reportItem.setResultintro(con[1]);
							}
							if (isWeidu && txt.contains("心理建议") && i == 3) {
								String[] con = txt.split("】");
								reportItem.setSuggestion(con[1]);
								sortnum++;
								reportItem.setSortnum(sortnum);
								itemlist.add(reportItem);								
								isWeidu = false;
							}
							if (isSel) {
								itemscorestr+=txt+"#";
							}
						}
					}
				}
			}
			ins.close();
	/*	} catch (Exception e) {
			e.printStackTrace();
			return null;
		}*/		
		report.setCheckitems(itemlist);	
		report.setItemscorestr(itemscorestr);
		return report;
	}
	
	public static void main(String[] args) {
		
//		try {//
//			VReportImport x = readWordFile("C:\\Users\\Administrator\\Desktop\\中学生心理健康诊断测验(MHT)-朱敏_87.doc");
//			System.out.println(x.getChecktime());
//			VReportImport y = readWordFile("C:\\Users\\Administrator\\Desktop\\艾森克人格问卷-少年版（EPQ）-朱敏_28.doc");
//			System.out.println(y.getChecktime());
//		} catch (IOException e) {
//			e.printStackTrace();
//		}

	}

}